#!/bin/bash
###############################################################################
# @用例ID: 20230524-163554-963002542
# @用例名称: test-mariadb
# @用例级别: 3
# @用例标签:
# @用例类型: 功能
###############################################################################
[ -z "$TST_TS_TOPDIR" ] && {
    TST_TS_TOPDIR="$(realpath "$(dirname "$0")/..")"
    export TST_TS_TOPDIR
}
source "${TST_TS_TOPDIR}/tst_common/lib/common.sh" || exit 1
###############################################################################

g_tmpdir="$(mktemp -d)"
# 记录初始mariadb状态，以供tc_teardown函数中恢复最初状态
g_mariadb_status=""

tc_setup() {
    msg "this is tc_setup"
    # @预置条件: 系统已安装 mariadb 软件包，并将其service名字命名为mysql

    # 检查 mariadb 是否已成功安装并获取 mariadb 版本号
    mariadb_installed=$(mariadb --version)
    assert_true [ $? -eq 0 ]
    mariadb_version=$(echo $mariadb_installed | awk '{print $5}')

    # 检查 mariadb 是否已经启动
    mariadb_status=$(systemctl is-active mysql)
    if [ "${mariadb_status}" == "active" ]; then
        g_mariadb_status="active"
        echo "MariaDB server version ${mariadb_version} is already running!"
    else
        # 启动 mariadb Server
        systemctl start mysql
        assert_true [ $? -eq 0 ]

        # 检查 mariadb 是否启动成功
        mysqladmin ping > /dev/null 2>&1
        assert_true [ $? -eq 0 ]
        echo "MariaDB server version ${mariadb_version} started successfully!"
    fi
}


do_test() {
    msg "this is do_test"
    # @测试步骤:1: 找到mariadb的安装位置以及官方测试脚本，运行 mariadb 官方测试用例
    # @预期结果:1: 能找到官方测试用例，且官方测试用例全部通过

    mariadb_install_path=$(which mariadb)
    mariadb_install_dir=$(dirname $mariadb_install_path)
    test_dir="${mariadb_install_dir}/../mysql-test"
    assert_true [ $? -eq 0 ]
    cd "$test_dir"
    sudo ./mariadb-test-run.pl --force --max-test-fail=0
    assert_true [ $? -eq 0 ]
    echo "All tests passed!"
    return 0
}


tc_teardown() {
    msg "this is tc_teardown"
    systemctl stop mysql
    assert_true [ $? -eq 0 ]
    echo "MySQL service stopped successfully."

    # 恢复 mariadb 初始状态
    if [ "${g_mariadb_status}" == "active" ]; then
        systemctl start mysql
        assert_true [ $? -eq 0 ]
        echo "MySQL service started successfully."
    fi

    rm -rfv "$g_tmpdir" || return 1
    return 0
}


###############################################################################
tst_main "$@"
###############################################################################
